package com.muqi.app.qlearn.fragments;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.XAxis.XAxisPosition;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.components.YAxis.YAxisLabelPosition;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.formatter.LargeValueFormatter;
import com.github.mikephil.charting.formatter.YAxisValueFormatter;
import com.muqi.app.network.http.MyAsyncHttp;
import com.muqi.app.network.http.MyAsyncHttp.AsyncCallBackListener;
import com.muqi.app.network.http.ParamsUtils;
import com.muqi.app.network.http.MyAsyncHttp.RESULTCODE;
import com.muqi.app.network.http.ResponseUtils;
import com.muqi.app.project.contants.NetWorkApi;
import com.muqi.app.project.utils.NumberFormatUtil;
import com.muqi.app.qlearn.adapter.RewardsAndMovableAdapter;
import com.muqi.app.qlearn.adapter.RewardsAndMovableAdapter.OnNextArrow;
import com.muqi.app.qlearn.modles.GrowRewardAndMoveInfo;
import com.muqi.app.qlearn.modles.RecordDetailBean;
import com.muqi.app.qlearn.publish.RecordDetailActivity;
import com.muqi.app.qlearn.student.BaseChildFragment;
import com.muqi.app.qlearn.student.R;

import com.muqi.app.user.db.ChildBean;
import com.muqi.app.user.widget.MyListView;
import com.muqi.app.widget.pulltorefresh.XListView;
import com.muqi.app.widget.pulltorefresh2.XScrollView;

public class RewardsAndMovableFragment extends BaseChildFragment implements
		OnClickListener,XScrollView.IXScrollViewListener, OnItemClickListener,
		OnNextArrow {
	public static final String REQUEST_REFRSH_CODE = "refrsh_order_list";
	protected int uiType = 0; /* 0 获奖统计 1活动统计 */
	private MyListView mListview;
	private TextView mTv_des_title;
	private TextView mTv_title;
	private int page = 1;

	private List<RecordDetailBean> infos = new ArrayList<RecordDetailBean>();
	private RewardsAndMovableAdapter adapter;
	private BarChart mChart;
	private ImageView iv_type;
	private XScrollView mScrollView;

	@Override
	public void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle args = getArguments();
		uiType = args.getInt("type");
	}

	@SuppressLint("InflateParams")
	@Override
	@Nullable
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

		return LayoutInflater.from(mActivity).inflate(
				R.layout.fragment_rewardsandmovable, null);

	}

	@Override
	public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		mTv_title=(TextView) getActivity().findViewById(R.id.tv_title);
		mScrollView = (XScrollView)view.findViewById(R.id.xMyScrollView);
		mScrollView.setPullRefreshEnable(true);
		mScrollView.setPullLoadEnable(false);
		mScrollView.setAutoLoadEnable(true);
		mScrollView.setIXScrollViewListener(this);
		mScrollView.setRefreshTime("刚刚");
		
		View contentView = LayoutInflater.from(mActivity).inflate(R.layout.fragment_rewardsandmovable_content, null);
		mScrollView.setView(contentView);
		mChart=(BarChart)contentView.findViewById(R.id.barchart);
        iv_type=(ImageView) contentView.findViewById(R.id.reword_iv);
        mTv_des_title=(TextView) contentView.findViewById(R.id.tv_statis_title);
 
		mListview=(MyListView) contentView.findViewById(R.id.reword_lv);
		mListview.setAdapter(null);
        mListview.setOnItemClickListener(this);
		if (uiType == 0) {
			iv_type.setImageResource(R.drawable.icon_reword);
			mTv_des_title.setText("获奖统计");
			mTv_title.setText("获奖统计");
		} else if (uiType == 1) {
			iv_type.setImageResource(R.drawable.icon_move);
			mTv_des_title.setText("活动统计");
			mTv_title.setText("活动统计");
		}

		if (myChildren != null && myChildren.size() > 0) {
			if (myChildren.size() > 1) {
//				Drawable drawable = getResources().getDrawable(
//						R.drawable.btn_down_white);
//				drawable.setBounds(0, 0, drawable.getMinimumWidth(),
//						drawable.getMinimumHeight());
//				mTv_title.setCompoundDrawables(null, null, drawable, null);
//				mTv_title.setOnClickListener(this);
			}

		}
		
		initChart();
		loadData();

	}

	/**
	 * 加载数据
	 */
	private void loadData() {
		getChartData();
		getListData();
	}

	private void getListData() {
		HashMap<String, Object> sendMap = new HashMap<String, Object>();
		sendMap.put("token", mSpUtil.getToken());
		sendMap.put("school_id", mSpUtil.getChildSchoolId());
		sendMap.put("grade_id", mSpUtil.getChildGradeId());
		sendMap.put("class_manager_id", mSpUtil.getChildClassId());
		sendMap.put("student_id", mSpUtil.getCurrentChildId());
		sendMap.put("page", page);
		String requestUrl = "";
		if (uiType == 0) {
			requestUrl = ParamsUtils.buildParams(
					NetWorkApi.GET_REWORD_STATISC_LIST, sendMap);
		} else {
			requestUrl = ParamsUtils.buildParams(
					NetWorkApi.GET_MOVE_STATISC_LIST, sendMap);
		}
		MyAsyncHttp.get(mActivity, requestUrl, new AsyncCallBackListener() {

			@Override
			public void onAsyncCallBack(RESULTCODE resuleCode, String request,String result) {
				mScrollView.stopLoadMore();
				mScrollView.stopRefresh();
				mScrollView.setPullLoadEnable(false);
				if (resuleCode == RESULTCODE.SUCCESS) {
					ArrayList<RecordDetailBean> tempList = ResponseUtils.getRecordListDetails(mActivity, result);
					if (tempList != null) {
						if(page == 1){
							if(tempList.size()==0){
								showEmpty("该学生还没有相关记录");
								return ;
							}else{
								hidEmpty();
							}
							infos = tempList;
							if(adapter!=null)adapter=null;
							adapter = new RewardsAndMovableAdapter(mActivity, infos);
							adapter.setOnNextArrow(RewardsAndMovableFragment.this);
							mListview.setAdapter(adapter);
						}else{
							for (RecordDetailBean recordDetailBean : tempList) {
								infos.add(recordDetailBean);
							}
							if(adapter!=null) adapter.notifyDataSetChanged();
						}
						
						if (tempList.size() >= 10) {
							mScrollView.setPullLoadEnable(true);
							page++;
						} else {
							mScrollView.setPullLoadEnable(false);
						}
						if (infos.size() > 0) {
							iv_type.setVisibility(View.VISIBLE);
						}
					}
				}

			}
		});

	}

	private void getChartData() {
		HashMap<String, Object> sendMap = new HashMap<String, Object>();
		sendMap.put("token", mSpUtil.getToken());
		sendMap.put("school_id", mSpUtil.getChildSchoolId());
		sendMap.put("grade_id", mSpUtil.getChildGradeId());
		sendMap.put("class_manager_id", mSpUtil.getChildClassId());
		sendMap.put("student_id", mSpUtil.getCurrentChildId());
		String requestUrl = "";
		if (uiType == 0) {
			requestUrl = ParamsUtils.buildParams(NetWorkApi.GET_REWORD_STATISC,
					sendMap);
		} else {
			requestUrl = ParamsUtils.buildParams(NetWorkApi.GET_MOVE_STATISC,
					sendMap);
		}
		MyAsyncHttp.get(mActivity, requestUrl, new AsyncCallBackListener() {

			@Override
			public void onAsyncCallBack(RESULTCODE resuleCode, String request,
					String result) {
				if (resuleCode == RESULTCODE.SUCCESS) {
					Log.e("===", result);
					ArrayList<GrowRewardAndMoveInfo> infos = ResponseUtils
							.getGrowStatisticsInfos(mActivity, result);
					if (infos != null) {
						showChart(mChart, infos);
					}
					// Log.e("===", infos.size()+""+uiType);

				}

			}

		});
	}

	private void initChart() {
		mChart.setTouchEnabled(false);
		mChart.setDrawBarShadow(false);
		mChart.setDrawValueAboveBar(true);
		mChart.setDescription("");
		mChart.setMaxVisibleValueCount(60);

		mChart.setPinchZoom(false);
		mChart.setDrawGridBackground(false);

		XAxis xAxis = mChart.getXAxis();
		xAxis.setPosition(XAxisPosition.BOTTOM);
		xAxis.setDrawGridLines(false);
		xAxis.setSpaceBetweenLabels(2);
		xAxis.setTextColor(mActivity.getResources().getColor(
				R.color.statis_reword_color));
		xAxis.setTextSize(12f);

		YAxis leftAxis = mChart.getAxisLeft();

		leftAxis.setLabelCount(5, true);
		leftAxis.setAxisMaxValue(10f);
		leftAxis.setPosition(YAxisLabelPosition.OUTSIDE_CHART);
		leftAxis.setSpaceTop(15f);
		leftAxis.setAxisMinValue(0f); // this replaces setStartAtZero(true)
		leftAxis.setTextColor(mActivity.getResources().getColor(
				R.color.statis_reword_color));
		leftAxis.setTextSize(12f);
		leftAxis.setValueFormatter(new YAxisValueFormatter() {
			
			@Override
			public String getFormattedValue(float value, YAxis yAxis) {
				// TODO Auto-generated method stub
				return (int)value+"";
			}
		});

		YAxis rightAxis = mChart.getAxisRight();
		rightAxis.setEnabled(false);

		Legend l = mChart.getLegend();
		l.setEnabled(false);

	}

	private void showChart(BarChart mBarChart,
			ArrayList<GrowRewardAndMoveInfo> statisticsList) {
		ArrayList<String> xValues = new ArrayList<String>(); // xVals用来表示每个饼块上的内容
		ArrayList<BarEntry> yValues = new ArrayList<BarEntry>(); // yVals用来表示封装每个饼块的实际数据

		ArrayList<Float> y = new ArrayList<Float>();
		for (int i = 0; i < statisticsList.size(); i++) {

			xValues.add(statisticsList.get(i).desc);
			yValues.add(new BarEntry(NumberFormatUtil
					.getFloatFromString(statisticsList.get(i).data), i));
			y.add(NumberFormatUtil.getFloatFromString(statisticsList.get(i).data));

		}
		Collections.sort(y);
		YAxis leftAxis = mChart.getAxisLeft();
		float maxValue = y.get(y.size() - 1);
		int labelCount = 6;
		if (maxValue < 10) {
			maxValue = 10;
			leftAxis.setLabelCount(labelCount, true);
		} else {
			leftAxis.setLabelCount(8, false);
		}

		leftAxis.setAxisMaxValue(maxValue);
		BarDataSet set1;

		ArrayList<Integer> colors = new ArrayList<Integer>();

		// 图例颜色
		colors.add(Color.rgb(89, 115, 173));
		colors.add(Color.rgb(49, 223, 187));
		colors.add(Color.rgb(135, 179, 78));
		colors.add(Color.rgb(44, 158, 137));
		colors.add(Color.rgb(237, 149, 63));

		set1 = new BarDataSet(yValues, "");
		set1.setBarSpacePercent(35f);

		set1.setColors(colors);

		ArrayList<BarDataSet> dataSets = new ArrayList<BarDataSet>();
		dataSets.add(set1);

		BarData data = new BarData(xValues, dataSets);
		data.setValueTextSize(10f);
		data.setValueFormatter(new LargeValueFormatter());

		mChart.setData(data);
		mChart.invalidate();

	}

	@Override
	public void onClick(View v) {

	}

	@Override
	public void onRefresh() {
		mScrollView.setRefreshTime("刚刚");
		page = 1;
		getChartData();
		getListData();
	}

	@Override
	public void onLoadMore() {
		getListData();
	}

	//
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		if (infos != null) {
			RecordDetailBean bean = infos.get(arg2);
			if (bean != null) {
				Intent intent = new Intent(getActivity(),
						RecordDetailActivity.class);
				intent.putExtra(RecordDetailActivity.RECORD_ID, bean.id);
				startActivity(intent);
			}
		}
	}

	@Override
	public void onNextArrowClick(int position) {
	/*	if (infos != null) {
			RecordDetailBean bean = infos.get(position);
			if (bean != null) {
				Intent intent = new Intent(getActivity(),
						RecordDetailActivity.class);
				intent.putExtra(RecordDetailActivity.RECORD_ID, bean.id);
				startActivity(intent);
			}
		}*/

	}

	@Override
	protected void onChoiceChildResult(ChildBean myChild) {
		// TODO Auto-generated method stub

	}

}